<script lang="ts" setup>
import {onMounted, reactive, ref} from "vue";
import axios from "axios";
import {type FormItemRows, QForm} from "@meetjs/element-plus-kit";
import {Plus} from "@element-plus/icons-vue";
import type {UploadProps, UploadUserFile} from "element-plus";

const departmentOptions = [
  {label: '口腔内科', value: '口腔内科'},
  {label: '口腔外科', value: '口腔外科'},
  {label: '口腔正畸科', value: '口腔正畸科'},
  {label: '口腔修复科', value: '口腔修复科'},
  {label: '口腔种植科', value: '口腔种植科'},
  {label: '儿童口腔科', value: '儿童口腔科'},
  {label: '牙周病科', value: '牙周病科'},
  {label: '预防口腔科', value: '预防口腔科'},
  {label: '综合口腔科', value: '综合口腔科'}
];
const titleOptions = [
  {label: '主任医师', value: '主任医师'},
  {label: '副主任医师', value: '副主任医师'},
  {label: '主治医师', value: '主治医师'},
  {label: '医师', value: '医师'},
  {label: '助理医师', value: '助理医师'},
  {label: '实习医师', value: '实习医师'}
];
const expertiseOptions = [
  {label: '龋齿治疗', value: '龋齿治疗'},
  {label: '根管治疗', value: '根管治疗'},
  {label: '牙齿矫正', value: '牙齿矫正'},
  {label: '种植牙', value: '种植牙'},
  {label: '牙齿美白', value: '牙齿美白'},
  {label: '牙周病治疗', value: '牙周病治疗'},
  {label: '儿童牙病治疗', value: '儿童牙病治疗'},
  {label: '口腔修复', value: '口腔修复'},
  {label: '智齿拔除', value: '智齿拔除'},
  {label: '口腔预防保健', value: '口腔预防保健'}
];


const doctorInfo = reactive({
  qualificationCertificate: '',
  departments: '',
  fields: '',
  jobTitle: '',
  status: 0
})

const uploadImage = async (option: any) => {
  const formData = new FormData();
  formData.append('file', option.file);

  try {
    const res = await axios.post('/api/upload/img', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        token: localStorage.getItem("doctor-auth-token") || ''
      }
    });

    // ✅ 设置头像地址（用于提交）
    doctorInfo.qualificationCertificate = res.data.message;
    console.log(res)
    // ✅ 更新 fileList 中的 url 显示
    fileList.value = [];
    fileList.value = [
      {
        name: option.file.name,
        url: res.data.message,
      }
    ]

    // 通知上传成功（必须调用，否则 element upload 状态不更新）
    option.onSuccess(res.data, option.file);
  } catch (error) {
    option.onError(error);
  }
};

const Apply = () => {
  isShowAuth.value = true
}
const isShowAuth = ref(false)
const headers = {
  token: localStorage.getItem("doctor-auth-token")
}
const getDoctorInfo = () => {
  axios.post("/api/doctor/info/info", {}, {headers})
      .then(res => {
        console.log(res);
        const msg = res.data.message
        doctorInfo.departments = msg.departments ? msg.departments : ''
        doctorInfo.fields = msg.fields ? msg.fields : ''
        doctorInfo.jobTitle = msg.jobTitle ? msg.jobTitle : ''
        doctorInfo.qualificationCertificate = msg.qualificationCertificate ? msg.qualificationCertificate : ''
        doctorInfo.status = msg.status
        if (msg.qualificationCertificate) {
          fileList.value = [
            {
              name: "资格证书",
              url: msg.qualificationCertificate
            }
          ]
        }
      })
}
const applyDoctor = () => {
  const data = doctorInfo
  console.log(doctorInfo);
  axios.post("/api/doctor/info/apply", data, {headers})
      .then(res => {
        console.log(res);
        isShowAuth.value = false
        getDoctorInfo()
      })
}
const closeQform = () =>{
  isShowAuth.value = false
}

onMounted(() => {
  getDoctorInfo()
})

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const fileList = ref<UploadUserFile[]>([])

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

const formOptions = ref<FormItemRows[]>([
  {type: "select-v2", label: "部门", prop: "departments", options: departmentOptions},
  {type: "select-v2", label: "职称", prop: "jobTitle", options: titleOptions},
  {type: "select-v2", label: "领域", prop: "fields", options: expertiseOptions},
  {type: "slot", label: "资格证书", prop: "customslot",},
]);
</script>

<template>
  <div>
    <el-card style="max-width: 480px">
      <template #header>
        <div class="card-header">
          <span>医生审核结果</span>
        </div>
      </template>
      <div style="font-size: 22px">
        当前医师审核的状态：{{
          doctorInfo.status == 0
              ? "没有审核过"
              : doctorInfo.status == 1
                  ? "正在审核"
                  : doctorInfo.status == -1
                      ? "审核未通过" : "审核已通过"
        }}
      </div>
      <div class="refuse_state">
        <el-button type="success" @click="getDoctorInfo">立即更新状态</el-button>
      </div>

      <template #footer>
        <el-button
            :disabled="doctorInfo.status == 2 || doctorInfo.status == 1"
            plain
            type="primary"
            @click="Apply"
        >
          {{
            doctorInfo.status == 0
                ? "立即审核"
                : doctorInfo.status == 1
                    ? "待审核中"
                    : doctorInfo.status == -1
                        ? "再次审核"
                        : doctorInfo.status == 2
                            ? "审核已通过"
                            : "审核异常"
          }}
        </el-button
        >
      </template>
    </el-card>
    <el-dialog v-model="isShowAuth" title="医师申请">
      <QForm ref="userInfo" :buttons="[ { label: '提交审核', type: 'submit' },{label:'取消',type: 'cancel'}]"
             :formOptions="formOptions" :model="doctorInfo" @cancel="closeQform"
             label-width="125px" style="width: 40vw;max-width: 700px" title="个人信息" @submit="applyDoctor">
        <template #customslot>
          <el-upload
              v-model:file-list="fileList"
              :http-request="uploadImage"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              limit="1"
              list-type="picture-card"
          >
            <el-icon>
              <Plus/>
            </el-icon>
          </el-upload>


          <el-dialog v-model="dialogVisible">
            <img :src="dialogImageUrl" alt="Preview Image" w-full/>
          </el-dialog>
        </template>
      </QForm>
    </el-dialog>

  </div>
</template>

<style lang="scss" scoped>

</style>
